package net.lainiao;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/11/10.
 */
public class ExampleClientThatLocks {
//    private final InterProcessMutex lock;
    private final InterProcessSemaphoreMutex lock;
    private final FakeLimitedResource resource;
    private final String clientName;

    public ExampleClientThatLocks(CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName) {
        this.resource = resource;
        this.clientName = clientName;
//        this.lock = new InterProcessMutex(client, lockPath);
        this.lock = new InterProcessSemaphoreMutex(client, lockPath);
    }

    public void doWork(long time, TimeUnit unit) throws Exception {
        if(!lock.acquire(time,unit)){
                throw new IllegalStateException(clientName+" could not acquire the lock");
        }
        if(!lock.acquire(time,unit)){
            throw new IllegalStateException(clientName+" could not acquire the lock");
        }

        try {
            System.out.println(clientName+" has the lock");
            System.out.println(clientName+" has the lock");
            resource.use();
        } finally {
            System.out.println(clientName+" releasing the lock");
            lock.release();
            System.out.println(clientName+" releasing the lock");
            lock.release();
        }

    }
}
